package cn.jtfadmin.base.lang.common.utils;


import cn.jtfadmin.base.lang.config.ApplicationHolder;
import org.apache.commons.beanutils.PropertyUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.core.convert.ConversionService;
import org.springframework.util.Assert;
import org.springframework.util.CollectionUtils;

import javax.validation.constraints.NotNull;
import java.beans.PropertyDescriptor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

/**
 * 反射工具
 * @author jtf
 * @since 0.0.1
 */
public class ReflectionUtils {

    /**
     * 获取字段值
     * @param target 目标对象
     * @param fieldName 目标字段名称
     * @return 字段值
     */
    public static Object getFieldValue(@NotNull Object target, @NotNull String fieldName){
        Objects.requireNonNull(target, "参数目标类不能为空");
        Objects.requireNonNull(fieldName, "参数字段名不能为空");
        try {
            return PropertyUtils.getProperty(target, fieldName);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }


    /**
     * 获取字段值
     * @param target 目标对象
     * @param fieldName 目标字段名称
     * @return
     */
    public static String getFieldValueStr(@NotNull Object target, @NotNull String fieldName){
        return String.valueOf(getFieldValue(target, fieldName));
    }



    public static List<Field> getDeclaredFields(Class<?> clazz) {
        List<Field> list = new ArrayList<>();
        org.springframework.util.ReflectionUtils.doWithFields(clazz, (t)->list.add(t));
        return list;
    }

    public static void setFieldValueIfPossibly(Object data, String fieldName, String value) {
        PropertyDescriptor propertyDescriptor = BeanUtils.getPropertyDescriptor(data.getClass(), fieldName);
        if(propertyDescriptor != null){

            Method writeMethod = propertyDescriptor.getWriteMethod();
            if(writeMethod != null){
                try {
                    if(Objects.isNull(value)){
                        writeMethod.invoke(data, null);
                    }else {
                        Class<?> propertyType = propertyDescriptor.getPropertyType();
                        Object v = ApplicationHolder.getApplicationContext().getBean(ConversionService.class)
                                .convert(value,propertyType);
                        writeMethod.invoke(data, v);
                    }

                } catch (IllegalAccessException e) {
                    e.printStackTrace();
                } catch (InvocationTargetException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
